﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace TestTcpServer;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private TcpListener? _tcpListener;
    private TcpClient? _client;
    private NetworkStream? _stream;
    private CancellationTokenSource? _cancellationTokenSource;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnClosed(EventArgs e)
    {
        _client?.Close();
        _tcpListener?.Stop();
    }

    private void Log(string message)
    {
        Dispatcher.Invoke(() =>
        {
            txtLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}\n");
            txtLog.ScrollToEnd();
        });
    }

    private void BtnStart_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            _cancellationTokenSource = new CancellationTokenSource();
            var port = int.Parse(txtPort.Text);
            _tcpListener = new TcpListener(IPAddress.Any, port);
            _tcpListener.Start();

            Log($"服务器启动，监听端口: {port}");

            btnStart.IsEnabled = false;
            btnStop.IsEnabled = true;

            // 开始接受客户端连接
            _ = Task.Run(async () => await AcceptClientsAsync(_cancellationTokenSource.Token));
        }
        catch (Exception ex)
        {
            Log($"启动服务器错误: {ex.Message}");
        }
    }

    private async Task AcceptClientsAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            try
            {
                _client = await _tcpListener!.AcceptTcpClientAsync(cancellationToken);
                Log("客户端已连接");

                _stream = _client.GetStream();
                _ = Task.Run(async () => await ReceiveDataAsync(_client, cancellationToken));
            }
            catch (OperationCanceledException)
            {
                break;
            }
            catch (Exception ex)
            {
                Log($"接受客户端错误: {ex.Message}");
            }
        }
    }

    private async Task ReceiveDataAsync(TcpClient client, CancellationToken cancellationToken)
    {
        var buffer = new byte[1024];

        try
        {
            while (!cancellationToken.IsCancellationRequested && client.Connected)
            {
                var bytesRead = await _stream!.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                if (bytesRead == 0) break;

                var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Log($"收到消息: {message}");
            }
        }
        catch (Exception ex)
        {
            Log($"接收数据错误: {ex.Message}");
        }
        finally
        {
            Log("客户端断开连接");
            client.Close();
        }
    }

    private async void BtnSend_Click(object sender, RoutedEventArgs e)
    {
        await SendMessage();
    }

    private async void TxtMessage_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Enter)
        {
            await SendMessage();
        }
    }

    private async Task SendMessage()
    {
        if (_client == null || !_client.Connected)
        {
            Log("没有连接的客户端");
            return;
        }

        var message = txtMessage.Text;
        if (string.IsNullOrWhiteSpace(message)) return;

        try
        {
            var data = Encoding.UTF8.GetBytes(message);
            await _stream!.WriteAsync(data, 0, data.Length);
            Log($"发送消息: {message}");
            // txtMessage.Clear();
        }
        catch (Exception ex)
        {
            Log($"发送消息错误: {ex.Message}");
        }
    }

    private void BtnStop_Click(object sender, RoutedEventArgs e)
    {
        _cancellationTokenSource?.Cancel();
        _tcpListener?.Stop();
        _client?.Close();

        Log("服务器已停止");
        btnStart.IsEnabled = true;
        btnStop.IsEnabled = false;
    }
}